import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import axios from "axios"
export default new Vuex.Store({
  state: {
    listitem: [],
    shoppingList: JSON.parse(localStorage.getItem('shoppingList')) || [],
    checkboxList: false,  //全选
    allmoney: 0 //  总价
  },
  mutations: {
    LISTITEM(state, items) {
      state.listitem = [...items]
    },
    SHOPPING(state, item) {
      var jia = false
      state.shoppingList.map((ele) => {
        if (ele.pid == item.pid) {
          ele.count++;
          jia = true
        }
      })
      if (!jia) {
        item.count = 1;
        item.checked = false;
        state.shoppingList.push(item)
      }
      localStorage.setItem('shoppingList', JSON.stringify(state.shoppingList))
    },
    // 全选
    CHECKALL(state, check) {
      state.checkboxList = check
      state.shoppingList.map((ele) => {
        ele.checked = check
      })

      // 总价
      state.allmoney = 0
      state.shoppingList.map((ele) => {
        if (ele.checked) {
          state.allmoney += ele.count * ele.price
        }
      })
      localStorage.setItem('shoppingList', JSON.stringify(state.shoppingList))
    },
    // 复选框
    CHECKBOX(state, item) {
      item.checked = !item.checked
      state.shoppingList.map((ele) => {
        if (ele.pid == item.pid) {
          ele.checked = item.checked
        }
      })
      let All = state.shoppingList.every((ele) => {
        return ele.checked == true
      })
      state.checkboxList = All

      // 总价
      state.allmoney = 0
      state.shoppingList.map((ele) => {
        if (ele.checked) {
          state.allmoney += ele.count * ele.price
        }
      })
      localStorage.setItem('shoppingList', JSON.stringify(state.shoppingList))
    },
    DELEITEM(state, index) {
      state.shoppingList.splice(index, 1)
      localStorage.setItem('shoppingList', JSON.stringify(state.shoppingList))
    }
  },
  actions: {
    LISTITEM(context) {
      axios.get('./huawei.json').then((res) => {
        console.log(res.data);
        context.commit('LISTITEM', res.data)
      }).catch((err) => {
        console.log(err);
      })
    },
    SHOPPING(context, item) {
      context.commit('SHOPPING', item)
    },
    // 全选
    CHECKALL(context, check) {
      context.commit('CHECKALL', check)
    },
    // 复选框
    CHECKBOX(context, item) {
      context.commit('CHECKBOX', item)
    },
    DELEITEM(context, index){
      context.commit('DELEITEM', index)
    }

  },
  modules: {
  }
})
